<template>
  <div class="login">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title"><img v-if="logo" :src="logo" class="sidebar-logo"> 晴空小志</h3>
      <el-form-item prop="username">
        <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号">
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon"/>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          auto-complete="off"
          placeholder="密码"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon"/>
        </el-input>
      </el-form-item>
      <el-form-item prop="code">
        <el-input
          v-model="loginForm.code"
          auto-complete="off"
          placeholder="验证码"
          style="width: 63%"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon"/>
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" @click="getCode"/>
        </div>
      </el-form-item>
      <!--双向绑定-->
      <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 35px;">记住密码</el-checkbox>
      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width:80%;display:block;margin:0 auto"
          @click.native.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2020-2021 Sky All Rights Reserved.</span>
    </div>
  </div>
</template>

<script>
  import logoImg from '@/assets/logo/logo.png'
  //导入获取验证码方法
  import { getCodeImg } from '@/api/login'
  import Cookies from 'js-cookie'
  //
  import { encrypt, decrypt } from '@/utils/jsencrypt'

  export default {
    name: 'Login',
    data() {
      return {
        logo: logoImg,
        codeUrl: '',
        cookiePassword: '',
        loginForm: {
          username: 'swing',
          password: 'qqhzn.000',
          rememberMe: false,
          code: '',
          uuid: ''
        },
        //表单验证
        loginRules: {
          username: [
            { required: true, trigger: 'blur', message: '用户名不能为空' }
          ],
          password: [
            { required: true, trigger: 'blur', message: '密码不能为空' }
          ],
          code: [{ required: true, trigger: 'change', message: '验证码不能为空' }]
        },
        //登录按钮的加载效果
        loading: false,
        //
        redirect: undefined
      }
    },
    //键是需要观察的表达式，值是对应回调函数
    watch: {
      //$route 每一个路由都会有一个route对象，是一个局部的对象，可以获取对应的name,path,params,query等,属于data的一部分
      $route: {
        // 该回调会在任何被侦听的对象的 property 改变时被调用，不论其被嵌套多深
        handler: function(route) {
          /**
           * $route.path
           字符串，等于当前路由对象的路径，会被解析为绝对路径，如 "/home/news" 。
           $route.params
           对象，包含路由中的动态片段和全匹配片段的键值对
           $route.query
           对象，包含路由中查询参数的键值对。例如，对于/login?redirect=/index ，会得到 $route.query.redirect == 'index' 。
           $route.router
           路由规则所属的路由器（以及其所属的组件）。
           $route.matched
           数组，包含当前匹配的路径中所包含的所有片段所对应的配置参数对象。
           $route.name
           当前路径的名字，如果没有使用具名路径，则名字为空。
           */
          this.redirect = route.query && route.query.redirect
        },
        // 该回调将会在侦听开始之后被立即调用
        immediate: true
      }
    },
    created() {
      this.getCode()
      this.getCookie()
    },
    methods: {
      getCode() {
        getCodeImg().then(res => {
          this.codeUrl = 'data:image/gif;base64,' + res.img
          this.loginForm.uuid = res.uuid
        })
      },

      getCookie() {
        const username = Cookies.get('username')
        const password = Cookies.get('password')
        const rememberMe = Cookies.get('rememberMe')
        this.loginForm = {
          username: username === undefined ? this.loginForm.username : username,
          password: password === undefined ? this.loginForm.password : decrypt(password),
          rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
        }
      },
      //登录
      handleLogin() {
        //一个对象，持有注册过 ref attribute 的所有 DOM 元素和组件实例。
        this.$refs.loginForm.validate(valid => {
          //验证通过
          if (valid) {
            this.loading = true
            //记住我
            if (this.loginForm.rememberMe) {
              Cookies.set('username', this.loginForm.username, { expires: 120 })
              Cookies.set('password', encrypt(this.loginForm.password), { expires: 120 })
              Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 120 })
            } else {
              Cookies.remove('username')
              Cookies.remove('password')
              Cookies.remove('rememberMe')
            }
            this.$store
              .dispatch('Login', this.loginForm)
              //成功
              .then(() => {
                //向history栈中添加一个路由,切换路由
                this.$router.push({ path: this.redirect || '/' })
              })
              //失败
              .catch(() => {
                this.loading = false
                this.getCode()
              })
          }
        })
      }
    }
  }

</script>

<style rel="stylesheet/scss" lang="scss">
  .sidebar-logo {
    width: 50px;
    height: 35px;
    vertical-align: middle;
    margin-right: 12px;
  }
  .login {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    background-image: url("../assets/image/login-background.jpg");
    background-size: cover;
  }

  .title {
    margin: 0px auto 30px auto;
    text-align: center;
    color: #707070;
  }

  .login-form {
    border-radius: 6px;
    background: #ffffff;
    width: 400px;
    padding: 25px 25px 5px 25px;

    .el-input {
      height: 38px;

      input {
        height: 38px;
      }
    }

    .input-icon {
      height: 39px;
      width: 14px;
      margin-left: 2px;
    }
  }

  .login-tip {
    font-size: 13px;
    text-align: center;
    color: #bfbfbf;
  }

  .login-code {
    width: 33%;
    height: 38px;
    float: right;

    img {
      cursor: pointer;
      vertical-align: middle;
    }
  }

  .el-login-footer {
    height: 40px;
    line-height: 40px;
    position: fixed;
    bottom: 0;
    width: 100%;
    text-align: center;
    color: #fff;
    font-family: Arial;
    font-size: 12px;
    letter-spacing: 1px;
  }
</style>
